<?php
/**
 *description:快递、快运
 *author:李飞@天众科技
 *time:2016/05/15
 */

namespace Admin\Controller;
use Think\Controller;
class EmsController extends CommonController {
	
	
	// public function test(){
		// $aa="affafsf";
		// $arr=explode(',',$aa);
		// dump($arr);
	// }
	
	public function index(){
		$this->display();
    }

	public function emsfee(){
		$region=M('region');
		$region_list=$region->where(array('type'=>1))->select();
		$this->assign('region_list',$region_list);
		$this->display();
    }

	public function fee(){
		$m=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
		$ems_list=$m->where(array('status'=>1))->select();
		$this->assign('ems_list',$ems_list);
		
		$bc=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'));
		$bc_list=$bc->where(array('status'=>1))->select();
		$this->assign('bc_list',$bc_list);
		
		$this->display();
    }
	//获取面单列表数据(一般订单)
	public function get_printorder(){
		$m=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('Pushordergoods',C('DB_PRS'),C('DB_DEPOT'));

        $ck=A('CheckInput');
        //搜索条件
        $map=array();
		// $map['pick_status']=0;//未生成波次单
		//拦截
		$Outbound=A('Outbound');
		$inter_list=$Outbound->zintercepted();//拦截订单列表
		$cc=count($inter_list);//拦截订单数量
		if($cc){ //cc大于0，则说明有拦截订单
			foreach($inter_list as $key=>$val){
				$arr[$key]=$val['order_no'];
			}
			$map['m.order_no']=array('not in',$arr); //移除拦截订单
		}
		$order_no=I('order_no','',trim);
		$mailNo=I('mailNo','',trim);
		$receiveMan=I('receiveMan','',trim);
		$print_status=I('print_status','',trim);
		$start_time=I('start_time','',trim);
		$end_time=I('end_time','',trim);
		$ems_name=I('ems_name','',trim);
		$has_weight=I('has_weight','',trim);
		$merchant_code=I('merchant_code','',trim);
		
		if($has_weight==1){
			$where['_string']="p.pack_weight is not null";
			$where['_logic'] = 'and';
			$map['_complex'] = $where;
		}
		if($has_weight==2){
			$where['_string']="p.pack_weight is null";
			$where['_logic'] = 'and';
			$map['_complex'] = $where;
		}
		
        $goods_name=I('goods_name','',trim);
		$number=I('nums','',trim);
		
		$map['m.order_cate']=1;
		!empty($order_no)?$map['m.order_no']=array('like','%'.$order_no.'%'):'';
        !empty($mailNo)?$map['m.logistics_no']=array('like','%'.$mailNo.'%'):'';
		!empty($receiveMan)?$map['m.user_name']=array('like','%'.$receiveMan.'%'):'';
		!empty($start_time)?$start_time = strtotime($start_time):$start_time=0;
		!empty($end_time)?$end_time = strtotime($end_time):$end_time =time();
		!empty($ems_name)?$map['m.logiscompany_name']=$ems_name:'';
		$map['_string'] = "m.add_time>=$start_time AND m.add_time<=$end_time";
		
		
        $page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  

        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);

		if(!empty($merchant_code)){
			$merchant_code=substr($merchant_code,0,9);
			$buildsql=$n->field('order_id')->where(array('left(goods_no,9)'=>$merchant_code))->group('order_id')->select(false);
			
			$buildsql2=$m->alias('m')->field('m.id,m.erp_code,m.order_no,m.logistics_no,m.user_name,m.user_phone,m.province,m.city,m.user_address,m.ems_fee,m.ems_fee_rate,m.logiscompany_name,m.add_time,p.pack_weight')->join('__PACKING__ p on m.order_no=p.order_no','LEFT')->select(false);
			
			$countsql="select a.id,a.erp_code,a.order_no,a.logistics_no,a.user_name,a.user_phone,a.province,a.city,a.user_address,a.ems_fee,a.ems_fee_rate,a.logiscompany_name,a.add_time,a.pack_weight from ".$buildsql2." a left join ".$buildsql." b on a.id=b.order_id ";
			
			$sql="select a.id,a.erp_code,a.order_no,a.logistics_no,a.user_name,a.user_phone,a.province,a.city,a.user_address,a.ems_fee,a.ems_fee_rate,a.logiscompany_name,a.add_time,a.pack_weight from ".$buildsql2." a left join ".$buildsql." b on a.id=b.order_id order by ".$sort." ".$order." limit ".($page-1)*$rows.",".$rows;

			$Model =M('',C('DB_PRS'),C('DB_DEPOT'));
			$count=$Model->execute($countsql);
			$info=$Model->query($sql);
			// dump($info);
			// echo $sql;
			// die;
		}else{
			$count=$m->alias('m')->field('m.id,m.erp_code,m.order_no,m.logistics_no,m.user_name,m.user_phone,m.province,m.city,m.user_address,m.ems_fee,m.ems_fee_rate,m.logiscompany_name,m.add_time,p.pack_weight')->join('__PACKING__ p on m.order_no=p.order_no','LEFT')->count();

			if(empty($map)){
				$info=$m->alias('m')->field('m.id,m.erp_code,m.order_no,m.logistics_no,m.user_name,m.user_phone,m.province,m.city,m.user_address,m.ems_fee,m.ems_fee_rate,m.logiscompany_name,m.add_time,p.pack_weight')->join('__PACKING__ p on m.order_no=p.order_no','LEFT')->page($page,$rows)->order('m.'.$sort.' '.$order)->select();
			}else{
				$info=$m->alias('m')->field('m.id,m.erp_code,m.order_no,m.logistics_no,m.user_name,m.user_phone,m.province,m.city,m.user_address,m.ems_fee,m.ems_fee_rate,m.logiscompany_name,m.add_time,p.pack_weight')->join('__PACKING__ p on m.order_no=p.order_no','LEFT')->where($map)->page($page,$rows)->order('m.'.$sort.' '.$order)->select();
			}
		}

		
		// echo $m->getlastsql();
		// die;
		//导出Excel
		$excel=I('excel');
		$count_avg=0;
        foreach($info as $k=>$v){
			if(!empty($excel)){ //导出Excel
				$info[$k]['logistics_no']=" ".$v['logistics_no'];//转字符串
				$info[$k]['user_phone']=" ".$v['user_phone'];//转字符串
			}
			if(!empty($v['add_time'])){
				$info[$k]['add_time']=date("Y-m-d H:i:s",$v['add_time']);
			}
			if($v['ems_fee']==0){//decimal类型0.0000转换为0
				$v['ems_fee']=0;
			}
			if($v['ems_fee_rate']==0){//decimal类型0.0000转换为0
				$v['ems_fee_rate']=0;
			}
			if(empty($v['ems_fee']) and !empty($v['pack_weight'])){
				$make_status=make_emsfee($v['logiscompany_name'],$v['province'],$v['pack_weight']);
				
				if($make_status['status']){
					$info[$k]['ems_fee']=$make_status['fee'];
				}else{
					$info[$k]['ems_fee']=0;
				}
			}
			if(empty($v['ems_fee_rate']) and !empty($info[$k]['ems_fee'])){
				$n_info=$n->field('goods_no')->where(array('order_id'=>$v['id']))->find();
				$merchant_code=substr($n_info['goods_no'],0,9);//商家编码
				$make_status=make_emsfee($v['logiscompany_name'],$v['province'],$v['pack_weight'],$merchant_code);
				// dump($make_status);
				// die;
				if($make_status['status']){
					$info[$k]['ems_fee_rate']=$make_status['fee'];
				}else{
					$info[$k]['ems_fee_rate']=0;
				}
			}

			if(empty($v['pack_weight'])){
				$info[$k]['has_weight']='否';
			}else{
				$info[$k]['has_weight']='是';
			}
			//汇总
			$total_ems_fee+=$info[$k]['ems_fee'];
			$count_avg=$k+1;
		}
		
		//平均

		$footer[0]['order_no']='平均';
		$footer[0]['ems_fee']=round($total_ems_fee/$count_avg,2);
		
		$footer[1]['order_no']='汇总';
		$footer[1]['ems_fee']=$total_ems_fee;
		
		if(!empty($excel)){ //导出Excel
			$xlsName  = "快递公司费用";
			$xlsCell  = array(
				array('id','ID'),
				array('order_no','订单编号'),
				array('logistics_no','电子面单号'),
				array('user_name','收件人姓名'),
				array('user_phone','收件人电话'),
				array('province','省'),
				array('city','市'),
				array('area','区'),
				array('user_address','收件人地址'),
				array('ems_fee','快递费用'),
				array('ems_fee_rate','客户快递费用'),
				array('logiscompany_name','快递公司'),
				array('has_weight','已称重'),
				array('add_time','推送时间')
			);
			exportExcel($xlsName,$xlsCell,$info);
			die;
		}
		// dump($info);
        if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
			$data['footer']=$footer;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
		// dump($data);
        $this->ajaxReturn($data);
    }
	//ems企业列表
	public function get_ems(){
        $ck=A('CheckInput');
		//参数验证
        $code=$ck->in('企业编码','code','ennumstr','',0,0);        
        $name=$ck->in('企业名称','name','cnennumstr','',0,0);
        $page=$ck->in('当前页','page','intval','1',0,0);
        $rows=$ck->in('每页记录数','rows','intval','',0,0);
		$status=I('status');
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
        //搜索条件
        $map=array();
		!empty($code)?$map['code']=array('like','%'.$code.'%'):'';
        !empty($name)?$map['name']=array('like','%'.$name.'%'):'';
		//获取数据
        $data=getTable('EmsCompany',$map,$page,$rows,$sort,$order,$status);
        $this->ajaxReturn($data);
    }
	
	//添加企业信息
    public function emsAdd(){
		$m=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');  
		$data['code']=I('code','','trim');
        $data['name']=I('name','','trim');
		$data['url']=I('url','','trim');
		$data['weight']=I('weight','','trim');
		$data['text']=I('text','','trim');
		$data['add_time']=time();
		$data['update_time']=time();
		//重复判断
		$map['code']=I('code');
		$duplicate=$m->where($map)->find();
		if($duplicate){
			$return['message']='企业编码已经存在';
            $return['status']=false;
            $this->ajaxReturn($return);
		}
        $insertId=$m->add($data);
		// echo $m->getlastsql();
		// die;
        if(!$insertId){
            $return['message']='添加企业失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='添加企业成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	
    //更新企业信息
    public function emsSave(){
		$m=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $ck=A('CheckInput');
        $data['name']=I('name','','trim');
		$data['url']=I('url','','trim');
		$data['text']=I('text','','trim');
		$data['weight']=I('weight','','trim');
		$data['merchant_code']=I('merchant_code','','trim');
		$data['default_status']=I('default_status','','trim');
		
		$data['update_time']=time();
		
		$name=$data['name'];
		$name=msubstr($name,0,2,"utf-8",false);
        $map['id']=$ck->in('ems企业id','id','intval','',1,0);
		//设默认判断
		if($data['default_status']){
			$dup=$m->where(array('name'=>array('like',"%$name%"),'default_status'=>1))->find();//同一快递重复
			// echo $m->getlastsql();
			if($dup){
				$return['message']='['.$name.']已有默认快递!';
				$return['status']=false; 
				$this->ajaxReturn($return);
			}
		}
        $result=$m->where($map)->save($data);
        if(false===$result){
            $return['message']='更新企业信息失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='更新企业信息成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	//更新快递费用
    public function emsfeeSave(){
		$m=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $ck=A('CheckInput');
		$data['ems_fee']=I('ems_fee','','trim');
        $map['id']=$ck->in('id','id','intval','',1,0);
		
        $result=$m->where($map)->save($data);
        if(false===$result){
            $return['message']='更新失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='更新成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	//审核ems企业
    public function get_examine(){
		$return=tableExamine('EmsCompany');
        $this->ajaxReturn($return);
    }
	//删除
    public function emsDel(){
		$m=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('EmsFee',C('DB_PRS'),C('DB_DEPOT'));
		if(!IS_POST) exit;
        $id=I('id');
		if(empty($id)) exit;//为空
        $arr=explode(',', $id);
        $map['id']=array('in',$arr);
		$m_list=$m->field('code')->where($map)->select();
		foreach($m_list as $k=>$v){
			$n_list=$n->where(array('ems_code'=>$v['code']))->select();
			if(!empty($n_list)){
				$return['message']=$v['code'].'请先删除对应的费用模板!';
				$return['status']=false;  
				$this->ajaxReturn($return);
			}
		}
		$result=$m->where($map)->delete();
		if($result){
			$return['message']='删除成功!';
            $return['status']=true; 
		}else{
			$return['message']='删除失败!';
            $return['status']=false;  
		}
        $this->ajaxReturn($return);
    }
	//清空回收站
    public function emsClear(){
		$return=tableClear('EmsCompany');
        $this->ajaxReturn($return);
    }
	//恢复回收站数据
    public function emsUndo(){
		$return=tableUndo('EmsCompany');
        $this->ajaxReturn($return);
    }
	
	//ems企业列表
	public function get_fee(){
		$m=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
		//参数验证
        $area=I('area','','trim');        

        $page=$ck->in('当前页','page','intval','1',0,0);
        $rows=$ck->in('每页记录数','rows','intval','',0,0);
		$status=I('status');
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
        //搜索条件
        $map=array();
		!empty($area)?$map['area']=array('like','%'.$area.'%'):'';
		$id=I('id');
		$m_info=$m->field('code')->where(array('id'=>$id))->find();
		$map['ems_code']=$m_info['code'];
		// dump(I());
		// die;
		//获取数据
        $data=getTable('EmsFee',$map,$page,$rows,$sort,$order,$status);
        $this->ajaxReturn($data);
    }
	
	//添加企业信息
    public function feeAdd(){
		$m=M('EmsFee',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $data['area']=I('area','','trim');
		$company_id=I('company_id');
		$company_info=$n->field('code')->where(array('id'=>$company_id))->find();
		// dump(I());
		// die;
		$data['ems_code']=$company_info['code'];
		$data['first_weight']=I('first_weight','','trim');
		$data['second_weight']=I('second_weight','','trim');
		$data['first_price']=I('first_price','','trim');
		$data['second_price']=I('second_price','','trim');
		
		$data['first_weight_t']=I('first_weight_t','','trim');
		$data['second_weight_t']=I('second_weight_t','','trim');
		$data['first_price_t']=I('first_price_t','','trim');
		$data['second_price_t']=I('second_price_t','','trim');
		
		$data['add_time']=time();
		$data['update_time']=time();
		//重复判断
		$map['area']=I('area','','trim');
		$duplicate=$m->where($map)->find();
		if($duplicate){
			$return['message']='此目的地已经存在';
            $return['status']=false;
            $this->ajaxReturn($return);
		}
        $insertId=$m->add($data);
		// echo $m->getlastsql();
		// die;
        if(!$insertId){
            $return['message']='添加失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='添加成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	
    //更新信息
    public function feeSave(){
		$m=M('EmsFee',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('EmsCompany',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $ck=A('CheckInput');
        $data['area']=I('area','','trim');
		$company_id=I('company_id','','trim');
		$company_info=$n->field('code')->where(array('id'=>$company_id))->find();
		$data['first_weight']=I('first_weight','','trim');
		$data['second_weight']=I('second_weight','','trim');
		$data['first_price']=I('first_price','','trim');
		$data['second_price']=I('second_price','','trim');
		
		$data['first_weight_t']=I('first_weight_t','','trim');
		$data['second_weight_t']=I('second_weight_t','','trim');
		$data['first_price_t']=I('first_price_t','','trim');
		$data['second_price_t']=I('second_price_t','','trim');
		
		$data['update_time']=time();
        $map['id']=$ck->in('费用id','id','intval','',1,0);
		$map['ems_code']=$company_info['code'];
		
        $result=$m->where($map)->save($data);
        if(false===$result){
            $return['message']='更新信息失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='更新信息成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	/**
     * ajax检查ems企业编码是否存在
     * @author 李飞
     */
    public function checkFeeCode(){
		$return=tableCheckInputFunc('EmsFee','code','企业编码','val','ennumstr','',2,10);
        $this->ajaxReturn($return);        
    }
	//审核ems企业
    public function get_examinefee(){
		$return=tableExamine('EmsFee');
        $this->ajaxReturn($return);
    }
	//删除
    public function feeDel(){
		$m=M('EmsFee',C('DB_PRS'),C('DB_DEPOT'));
		if(!IS_POST) exit;
        $id=I('id');
		if(empty($id)) exit;//为空
        $arr=explode(',', $id);
        $map['id']=array('in',$arr);
		$result=$m->where($map)->delete();
		if($result){
			$return['message']='删除成功!';
            $return['status']=true; 
			$this->ajaxReturn($return);
		}else{
			$return['message']='删除失败!';
            $return['status']=false; 
			$this->ajaxReturn($return);			
		}
    }
	//清空回收站
    public function feeClear(){
		$return=tableClear('EmsFee');
        $this->ajaxReturn($return);
    }
	//恢复回收站数据
    public function feeUndo(){
		$return=tableUndo('EmsFee');
        $this->ajaxReturn($return);
    }
}